package com.suda.sudaexamsystem.service.impl;

import com.suda.sudaexamsystem.mapper.UserClazzMapper;
import com.suda.sudaexamsystem.mapper.UserMapper;
import com.suda.sudaexamsystem.pojo.Clazz;
import com.suda.sudaexamsystem.pojo.User;
import com.suda.sudaexamsystem.service.ClazzService;
import com.suda.sudaexamsystem.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserClazzMapper userClazzMapper;
    @Autowired
    private ClazzService clazzService;

    @Override
    @Transactional
    public void registerUser(User user) {
        userMapper.addUser(user);
    }

    @Override
    @Transactional
    public void deleteUser(int userId) {
        // 删除用户做题记录
        // 删除用户和角色的关联
        // 解散用户自己的班级
        List<Clazz> clazzList = clazzService.findOwnerClazzByUserId(userId);
        for (Clazz clazz : clazzList) {
            clazzService.deleteClazz(clazz.getId());
        }
        // 解除用户和班级的关联
        userClazzMapper.deleteUserAndClazzAssociation(userId);
        userMapper.deleteUser(userId);
    }

    // 该接口无法更新用户的权限 Role接口去管理
    @Override
    @Transactional
    public void updateUser(User user) {
        userMapper.updateUser(user);
    }

    @Override
    @Transactional
    public User findById(int userId) {
        return userMapper.findById(userId);
    }

    @Override
    @Transactional
    public User findByNameAndPassword(String name, String password) {
        return userMapper.findByNameAndPassword(name, password);
    }

    @Override
    @Transactional
    public List<User> findAll() {
        return userMapper.findAll();
    }

    @Override
    @Transactional
    public List<User> findUsersForClazzId(int clazzId) {
        return userMapper.findUsersByClazzId(clazzId);
    }

    @Override
    @Transactional
    public boolean isClazzContainsUser(int userId, int clazzId) {
        return userClazzMapper.isUserInClazz(userId, clazzId);
    }
}
